<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        width: 600px;
        height: 600px;
        border: 1px solid;
        margin: 0 auto;
        position: relative;
      }
    </style>
  </head>
  <body>
    <div class="container"></div>
    <script>
      // 贪吃蛇
      // 生成静态的蛇身体；
      // 1.定义方块类；用来生成蛇身体的；
      class Rect {
        constructor(x, y, color) {
          this.ele = document.createElement("div");
          this.ele.style.width = "50px";
          this.ele.style.height = "50px";
          this.ele.style.position = "absolute";
          this.ele.style.border = "1px solid";
          this.ele.style.left = x + "px";
          this.ele.style.top = y + "px";
          this.ele.style.backgroundColor = color;
        }
        addDom(container) {
          container.appendChild(this.ele);
        }
      }

      // let rect1 = new Rect(0,0,"blue");
      // let containerEle = document.querySelector(".container");
      // rect1.addDom(containerEle);

      // let rect2 = new Rect(50,0,"red");
      // rect2.addDom(containerEle);

      // 2.生成蛇类；
      class Snake {
        constructor() {
          this.body = [];
          this.createBody();
        }
        createBody() {
          for (let i = 0; i < 5; i++) {
            let rect;
            if (i == 4) {
              rect = new Rect(i * 50, 0, "red");
            } else {
              rect = new Rect(i * 50, 0, "blue");
            }
            this.body.push(rect);
          }
        }
        renderDom(container) {
          this.body.forEach((rect) => {
            rect.addDom(container);
          });
        }
      }

      let containerEle = document.querySelector(".container");
      let snake = new Snake();
      snake.renderDom(containerEle);
    </script>
  </body>
</html>
